﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace AppManagement.BusManagers
{
    #region Using
    using DevComponents.DotNetBar;
    using AppManagement.Helpers;
    using AppManagement.Models;
    using AppManagement.Repositories;
    using AppManagement.UsersManager;
    #endregion

    /// <summary>
    ///  manage loai don vi corresponding with menus in app
    /// </summary>
    public partial class FrmQuanLyBenhNhan: Office2007Form
    {
        //  event handler to transfer data to other forms
        public EventHandler Handler { get; set; }
        public string Criteria_MaBenhNhan { get; set; }
        public string Criteria_Ho { get; set; }
        public string Criteria_Ten { get; set; }
        // ---------------- E -----------------

        public FrmQuanLyBenhNhan(bool EnableBtnChon = false)
        {
            InitializeComponent();
            btnChon.Enabled = EnableBtnChon;
        }

        public FrmQuanLyBenhNhan(string mabenhnhan, string ho, string ten)
        {
            InitializeComponent();
            btnChon.Enabled = false;

            Criteria_MaBenhNhan = mabenhnhan;
            Criteria_Ho = ho;
            Criteria_Ten = ten;
        }

        private void FrmQuanLyBenhNhan_Load(object sender, EventArgs e)
        {
            if (Criteria_MaBenhNhan == null)
            {
                LoadData();
            }
            else
            {
                Search();
            }
        }

        public void Search()
        {
            var lstItem = BenhNhanRepository.Search(Criteria_MaBenhNhan, Criteria_Ho, Criteria_Ten);

            var dt = new DataTable();
            dt.Columns.Add("MaBN");
            dt.Columns.Add("HoTen");
            dt.Columns.Add("NgaySinh");
            dt.Columns.Add("GioiTinh");
            dt.Columns.Add("DTDD");
            dt.Columns.Add("TinhTrang");

            for (int i = 0; i < lstItem.Count; i++)
            {
                dt.Rows.Add(lstItem[i].MaBN, lstItem[i].ToString(), String.Format("{0:dd/MM/yyyy}", lstItem[i].NgaySinh), lstItem[i].GioiTinh == null ? "" : (lstItem[i].GioiTinh == true ? "Nam" : "Nữ"), lstItem[i].DienThoai, lstItem[i].TinhTrangToiKham);
            }

            DataView objTimeSheetDV = new System.Data.DataView(dt);
            objTimeSheetDV.AllowNew = false;
            dtgvDataList.AutoGenerateColumns = false;
            dtgvDataList.DataSource = objTimeSheetDV;

            dtgvDataList.ClearSelection();
        }

        private void btnThemMoi_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.INSERT, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (ActionAdd())
            {
                LoadData();
                MessageBox.Show("Lưu dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Lưu dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.DELETE, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (MessageBox.Show("Bạn có chắc chắn xóa dòng này không?", "Xóa", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                if (ActionDelete())
                {
                    LoadData();
                    EraseTextboxes();
                    MessageBox.Show("Xóa dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Xóa dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.UPDATE, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (ActionUpdate())
            {
                LoadData();
                MessageBox.Show("Cập nhật dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Cập nhật dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            EraseTextboxes();
        }

        private void dtgvDataList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dtgvDataList.SelectedRows == null || dtgvDataList.SelectedRows.Count == 0)
                return;
            txtMaBenhNhan.Text = dtgvDataList.SelectedRows[0].Cells["MaBN"].Value.ToString(); ;

            var item = BenhNhanRepository.SelectByID(txtMaBenhNhan.Text);
            LoadDetailInfo(item);
        }

        public void LoadDetailInfo(BenhNhan item)
        {
            txtHo.Text = item.Ho == null ? "" : item.Ho;
            txtTen.Text = item.Ten == null ? "" : item.Ten;
            txtNoiOHienTai.Text = item.DiaChi == null ? "" : item.DiaChi;
            txtNgheNghiep.Text = item.NgheNghiep == null ? "" : item.NgheNghiep;
            txtDTDD.Text = item.DienThoai == null ? "" : item.DienThoai;
            txtTinhTrang.Text = item.TinhTrangToiKham == null ? "" : item.TinhTrangToiKham;
            dtNgaySinh.Value = item.NgaySinh == null ? DateTime.MinValue : item.NgaySinh.Value;
            cbxGioiTinh.SelectedIndex = item.GioiTinh == null ? -1 : (item.GioiTinh.Value ? 0 : 1);
        }

        private void btnChon_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.CHOOSING, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var id = txtMaBenhNhan.Text;
            var BenhNhan = BenhNhanRepository.SelectByID(id);
            TransferDataInfo(this, new TransferSimpleDataEvent(id + "#" + BenhNhan.ToString()));
        }

        /// <summary>
        /// Load data from DB
        /// </summary>
        private void LoadData()
        {
            var lstItem = BenhNhanRepository.SelectAll();

            var dt = new DataTable();
            dt.Columns.Add("MaBN");
            dt.Columns.Add("HoTen");
            dt.Columns.Add("NgaySinh");
            dt.Columns.Add("GioiTinh");
            dt.Columns.Add("DTDD");
            dt.Columns.Add("TinhTrang");

            for (int i = 0; i < lstItem.Count; i++)
            {
                dt.Rows.Add(lstItem[i].MaBN, lstItem[i].ToString() , String.Format("{0:dd/MM/yyyy}", lstItem[i].NgaySinh), lstItem[i].GioiTinh == null ? "" : (lstItem[i].GioiTinh == true ? "Nam" : "Nữ"), lstItem[i].DienThoai, lstItem[i].TinhTrangToiKham);
            }

            DataView objTimeSheetDV = new System.Data.DataView(dt);
            objTimeSheetDV.AllowNew = false;
            dtgvDataList.AutoGenerateColumns = false;
            dtgvDataList.DataSource = objTimeSheetDV;

            dtgvDataList.ClearSelection();
        }

        /// <summary>
        /// Validate user input
        /// </summary>
        /// <param name="isUpdate"></param>
        /// <returns></returns>
        private bool ValidateInput(EnumUpdateMode mode, ref string errorText)
        {
            // Mode update -> checking MaBenhNhan is exists on textbox
            if (mode == EnumUpdateMode.UPDATE || mode == EnumUpdateMode.DELETE || mode == EnumUpdateMode.CHOOSING)
            {
                if (txtMaBenhNhan.Text == "")
                {
                    errorText = "Vui lòng chọn bệnh nhân";
                    return false;
                }
            }
            if (mode != EnumUpdateMode.DELETE)
            {
                if (txtHo.Text == "")
                {
                    errorText = "Vui lòng nhập họ bệnh nhân";
                    return false;
                }
                if (txtTen.Text == "")
                {
                    errorText = "Vui lòng nhập tên bệnh nhân";
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Add a new item to DB
        /// </summary>
        /// <returns></returns>
        private bool ActionAdd()
        {
            try
            {
                var item = new BenhNhan
                {
                    MaBN = txtMaBenhNhan.Text,
                    Ho = txtHo.Text,
                    Ten = txtTen.Text,
                    DiaChi = txtNoiOHienTai.Text,
                    NgheNghiep = txtNgheNghiep.Text,
                    DienThoai = txtDTDD.Text,
                    TinhTrangToiKham = txtTinhTrang.Text,
                    GioiTinh = cbxGioiTinh.SelectedIndex == 0 ? true : false
                };

                UpdateForeignKeys(item);

                if (!BenhNhanRepository.Insert(item))
                {
                    return false;
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Erase data in textboxes when mode is insert
        /// </summary>
        public void EraseTextboxes()
        {
            txtMaBenhNhan.Text = "";
            txtHo.Text = "";
            txtTen.Text = "";
            txtNoiOHienTai.Text = "";
            txtNgheNghiep.Text = "";
            txtDTDD.Text = "";
            txtTinhTrang.Text = "";
            cbxGioiTinh.SelectedIndex = -1;
            dtNgaySinh.Value = DateTime.MinValue;
            dtgvDataList.ClearSelection();
        }

        /// <summary>
        /// Update item with specificed ID
        /// </summary>
        /// <returns></returns>
        private bool ActionUpdate()
        {
            try
            {
                var item = BenhNhanRepository.SelectByID(txtMaBenhNhan.Text);
                item.Ho = txtHo.Text;
                item.Ten = txtTen.Text;
                item.DiaChi = txtNoiOHienTai.Text;
                item.NgheNghiep = txtNgheNghiep.Text;
                item.DienThoai = txtDTDD.Text;
                item.TinhTrangToiKham = txtTinhTrang.Text;
                item.GioiTinh = cbxGioiTinh.SelectedIndex == 0 ? true : false;

                UpdateForeignKeys(item);

                return BenhNhanRepository.Save();
            }
            catch
            {
                return false;
            }
        }

        public void UpdateForeignKeys(BenhNhan item)
        {
            if (dtNgaySinh.Value != DateTime.MinValue)
            {
                item.NgaySinh = dtNgaySinh.Value;
            }
        }

        /// <summary>
        /// Delete item with specified ID
        /// </summary>
        /// <returns></returns>
        private bool ActionDelete()
        {
            try
            {
                return BenhNhanRepository.Delete(txtMaBenhNhan.Text);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        ///  function is used to transfer data when event would be raised
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void TransferDataInfo(object sender, TransferSimpleDataEvent e)
        {
            this.Close();
            this.Handler(this, e);
        }

        private void btnXemBenhAn_Click(object sender, EventArgs e)
        {
            if (dtgvDataList.SelectedRows == null || dtgvDataList.SelectedRows.Count == 0)
                return;
            FrmLapPhieuKham frm = new FrmLapPhieuKham(dtgvDataList.SelectedRows[0].Cells["MaBN"].Value.ToString());
            frm.ShowDialog();
        }

        private void dtgvDataList_DoubleClick(object sender, EventArgs e)
        {
            if (dtgvDataList.SelectedRows == null || dtgvDataList.SelectedRows.Count == 0)
                return;
            FrmLapPhieuKham frm = new FrmLapPhieuKham(dtgvDataList.SelectedRows[0].Cells["MaBN"].Value.ToString());
            frm.ShowDialog();
        }
    }
}